home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 10755 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.7 KB  |  90 lines

  1. Path: news.interport.net!usenet
  2. From: yaron@interport.net (Adi)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Boolean evaluation operator
  5. Date: Sun, 10 Mar 1996 05:16:46 GMT
  6. Organization: Interport Communications Corp.
  7. Message-ID: <4hte6e$55k@park.interport.net>
  8. References: <4hqcnk$aoj@natasha.rmii.com>
  9. NNTP-Posting-Host: yaron.port.net
  10. X-Newsreader: Forte Free Agent 1.0.82
  11.  
  12. disch@aartronics.com wrote:
  13.  
  14. >We have a Boolean class that contains the following operator:
  15.  
  16. >    // Returns 1 if THIS Boolean Object is false, and 0 if THIS Boolean Object
  17. >    //  is true.
  18. >    int
  19. >    Boolean::operator!(); // No referenced object; operates on THIS
  20.  
  21. >When used in the following code fragment, compilation fails with the message
  22. >"Error testbed.cpp 47: Illegal structure operation in function main()":
  23.  
  24. >    Boolean     bTrue = T;
  25. >    Boolean     bFalse = F;
  26. >    if (!bFalse)
  27. >    {
  28. >        cout << "bFalse" << endl;
  29. >    }
  30. >    if (bTrue)
  31. >    {
  32. >        cout << "bTrue" << endl;
  33. >    }
  34.  
  35. >Is there a way to define an evaluation operator so that "if (bTrue)" will
  36. >compile and execute as expected?
  37.  
  38. >Any input would be greatly appreciated.
  39.  
  40. >Bob Dischner
  41. >Aartronics Corp
  42.  
  43.  
  44.  
  45. Try something like this :
  46.  
  47.  
  48. class Boolean {
  49.     public :
  50.         Boolean(unsigned int b = FALSE) 
  51.             : value(b) {}
  52.  
  53.         Boolean(const Boolean& b) 
  54.             : value(b.value) {}
  55.  
  56.         virtual ~Boolean() {}
  57.  
  58.         operator unsigned int() 
  59.         { 
  60.             return value; 
  61.         }
  62.  
  63.         Boolean& operator !() 
  64.         { 
  65.             value = !value; return *this; 
  66.         }
  67.  
  68.         Boolean& operator = (const Boolean& t) 
  69.         { 
  70.             value = t.value; 
  71.             return *this;
  72.         )
  73.  
  74.     protected :
  75.         unsigned int value;
  76. };
  77.  
  78.  
  79.  
  80. NOTE :
  81.  
  82. The important thing here is the cast operator to unsigned integer.
  83.  
  84.  
  85.  
  86. Adi Degani
  87. New-York, NY
  88.  
  89.  
  90.